<template>
  <NuxtLayout name="userCenter">
    <div class="bg-gray-800 rounded-lg p-6">
      <h2 class="text-2xl font-bold text-white mb-6">我的收藏</h2>

      <!-- 加载中 -->
      <div v-if="loading" class="text-center py-12">
        <el-icon class="is-loading" :size="32" color="#409EFF">
          <Loading />
        </el-icon>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!collectionList || collectionList.length === 0" class="text-center py-12">
        <el-empty description="暂无收藏内容">
          <el-button type="primary" @click="navigateTo('/')">去发现好片</el-button>
        </el-empty>
      </div>

      <!-- 收藏列表 -->
      <div v-else class="space-y-6">
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
          <div v-for="item in collectionList" :key="item.collectionId" class="relative">
            <MovieCard :movie="{
              movieId: item.movieId,
              title: item.movieTitle,
              poster: item.moviePoster,
              rating: item.movieRating
            }" />

            <!-- 取消收藏按钮 -->
            <el-button
              @click="handleRemoveCollection(item)"
              type="danger"
              :icon="Delete"
              circle
              size="small"
              class="absolute top-2 right-2 z-10"
            />

            <!-- 收藏时间 -->
            <div class="mt-2 text-xs text-gray-400 text-center">
              收藏于 {{ formatDate(item.createTime) }}
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="total > pageSize" class="mt-6 flex justify-center">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </NuxtLayout>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Loading } from '@element-plus/icons-vue'

definePageMeta({
  middleware: 'auth'
})

const userStore = useUserStore()
const loading = ref(false)
const collectionList = ref<any[]>([])
const pageNum = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 获取收藏列表
const getCollectionList = async () => {
  loading.value = true
  try {
    const data = await $fetch('/dev-api/member/collection/list', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
    })

    if (data.code === 200) {
      collectionList.value = data.rows || []
      total.value = data.total || 0
    }
  } catch (error: any) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error(error.data?.msg || '获取收藏列表失败')
  } finally {
    loading.value = false
  }
}

// 取消收藏
const handleRemoveCollection = async (item: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消收藏《${item.movieTitle}》吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const data = await $fetch(`/dev-api/member/collection/${item.collectionId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (data.code === 200) {
      ElMessage.success('取消收藏成功')
      await getCollectionList()
    } else {
      ElMessage.error(data.msg || '取消收藏失败')
    }
  } catch (error) {
    // 用户取消操作，不做处理
    if (error !== 'cancel') {
      console.error('取消收藏失败:', error)
    }
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getCollectionList()
}

const handlePageChange = (val: number) => {
  pageNum.value = val
  getCollectionList()
}

onMounted(() => {
  getCollectionList()
})

// SEO设置
useSeoMeta({
  title: '我的收藏',
  description: '查看您收藏的影片',
})
</script>

<style scoped>
:deep(.el-empty__description) {
  color: rgba(255, 255, 255, 0.6);
}

:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: rgba(255, 255, 255, 0.8);
  --el-pagination-button-disabled-bg-color: rgba(31, 41, 55, 0.5);
  --el-pagination-button-disabled-color: rgba(255, 255, 255, 0.3);
  --el-pagination-hover-color: #409EFF;
}
</style>